#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
#       api.py
#
#       Copyright (C) 2010  Catullus Cassius
#
#       This file is part of python-vkontakte-player.
#
#       This program is free software: you can redistribute it and/or modify
#       it under the terms of the GNU General Public License as published by
#       the Free Software Foundation, either version 3 of the License, or
#       (at your option) any later version.
#
#       This program is distributed in the hope that it will be useful,
#       but WITHOUT ANY WARRANTY; without even the implied warranty of
#       MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#       GNU General Public License for more details.
#
#       You should have received a copy of the GNU General Public License
#       along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
#
#       This code adapted from vkontakte (MIT license) developed by Mikhail Korobov <kmike84@gmail com>
#

import hashlib, urllib, urllib2
import simplejson as json
from functools import partial

import api_exception

api_url = 'http://api.vkontakte.ru/api.php'
interaction = {'v' : u'3.0', 'format' : u'JSON'}

def create_sig(method_params, session):
	keys = sorted(method_params.keys())
	params = "".join(["%s=%s" % (key, method_params[key]) for key in keys])
	params = session['mid'] + params + session['secret']
	return hashlib.md5(params.encode('utf-8')).hexdigest().decode('utf-8')

class Api(object):
	def __init__(self, api_id, session):
		self.api_id = unicode(api_id)
		self.session = {}
		for key in session.keys():
			self.session[key] = unicode(session[key])

	def get(self, method, **kwargs):
		params = kwargs
		params['method'] = method
		params['sig'] = create_sig(params, self.session)
		params['sid'] = self.session['sid']
		str_params = {}
		for key in params.keys():
			str_params[key] = params[key].encode('utf-8')
		data = urllib.urlencode(str_params)
		resp = json.loads(urllib2.urlopen(api_url, data).read())
		if 'error' in resp:
			raise api_exception.MethodErr(int(resp["error"]["error_code"]),
				resp["error"]["error_msg"],
				resp['error']['request_params'])
		return resp['response']

	def method(self, method, **kwargs):
		kwargs['method'] = method
		func = partial(self, **kwargs)
		return func(**kwargs)

	def __call__(self, **kwargs):
		method = unicode(kwargs.pop('method'))
		for key in kwargs.keys():
			kwargs[key] = unicode(kwargs[key])
		params = {}
		params['api_id'] = self.api_id
		params['format'] = interaction['format']
		params['v'] = interaction['v']
		params.update(kwargs)
		return self.get(method, **params)

	def __getattr__(self, attrname):
		return partial(self, method=attrname)
